//
//  YJAdvertiseView.swift
//  YJAdvertisingDemo
//
//  Created by Jim1024 on 2017/2/13.
//  Copyright © 2017年 Jim1024. All rights reserved.
//

import UIKit

let ADImageName = "ADImageName"
let ADUrl = "ADUrl"
let ADDeadline = "ADDeadline"
let ADTapActionNotification = NSNotification.Name(rawValue: "ADTapActionNotification")

class YJAdvertiseView: UIView {

    /// 广告图的显示时间
    var adShowTime: Int = 0
    /// 图片路径
    var imgFilePath: String? {
        didSet {
            adImagView.image = UIImage(contentsOfFile: imgFilePath!)
        }
    }
    /// 图片对应的url地址
    var imgLinkUrl: String?
    /// 广告图的有效时间
    var imgDeadline: String?
    
    fileprivate var count: Int = 0
    
    fileprivate var countTimer: Timer?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(adImagView)
        addSubview(countButton)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        print("YJAdvertiseView deinit")
    }
    
    func showAdvertiseView(time: Int) {
        adShowTime = time
        countButton.setTitle("跳过\(time)", for: .normal)
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM/dd/yyyy HH:mm"
        
        guard let imgDeadline = imgDeadline else {
            print("没有过期时间！")
            return
        }
        let deadlineDate = dateFormatter.date(from: imgDeadline)
        print("当前日期: \(Date()), 过期时间: \(deadlineDate)")
        
        let result = deadlineDate?.compare(Date())
        if result == ComparisonResult.orderedAscending {
            dismiss()
        } else {
            startTimer()
            let currentWindow = UIApplication.shared.delegate!.window
            currentWindow??.isHidden = false
            currentWindow??.addSubview(self)
        }
    }
    
    /// 根据图片名拼接文件路径
    class func getFilePath(imageName: String?) -> String? {
        if imageName != nil {
            let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last
            return path! + imageName!
        }
        return nil
    }
    
    /// 判断文件是否存在
    class func isFileExist(filePath: String?) -> Bool {
        let manager = FileManager.default
        if let filePath = filePath {
            return manager.fileExists(atPath: filePath)
        }
        return false
    }
    
    class func getAdvertisingImageData() {
        let imageArray = ["http://img1.126.net/channel6/2016/022471/0805/2.jpg?dpi=6401136", "http://image.woshipm.com/wp-files/2016/08/555670852352118156.jpg"]
        let imageUrl = imageArray[0]
        let imgLinkUrl = "www.baidu.com"
        let imgDeadline = "09/30/2017 14:25"
        
        let stringArr = imageUrl.components(separatedBy: "/")
        let imgName = stringArr.last
        
        let isExist = isFileExist(filePath: getFilePath(imageName: imgName!))
        if !isExist {
            downloadAdImage(imageUrl: imageUrl, imageName: imgName!, imgLinkUrl: imgLinkUrl, imgDeadline: imgDeadline)
        }
    }
    
    class func downloadAdImage(imageUrl: String, imageName: String, imgLinkUrl: String, imgDeadline: String) {
        DispatchQueue.global().async {
            guard let data = try? Data(contentsOf: URL(string: imageUrl)!) else {
                print("获取数据失败")
                return
            }
            let img = UIImage(data: data)
            let imgData = UIImageJPEGRepresentation(img!, 0)
            let fileUrl = URL(fileURLWithPath: getFilePath(imageName: imageName)!)
            
            do {
                try imgData?.write(to: fileUrl)
            } catch {
                print("写入文件失败 error: \(error)")
                return
            }
            
            if let oldName = UserDefaults.standard.string(forKey: ADImageName) {
                if imageName != oldName {
                    deleteOldImage()
                }
            }
            
            UserDefaults.standard.set(imageName, forKey: ADImageName)
            UserDefaults.standard.set(imgLinkUrl, forKey: ADUrl)
            UserDefaults.standard.set(imgDeadline, forKey: ADDeadline)
            UserDefaults.standard.synchronize()
        }
    }
    
    /// 删除旧图片
    class func deleteOldImage() {
        let imageName = UserDefaults.standard.string(forKey: ADImageName)
        if (imageName != nil) {
//            let filePath =
            try? FileManager.default.removeItem(atPath: getFilePath(imageName: imageName!)!)
            UserDefaults.standard.set("", forKey: ADImageName)
            UserDefaults.standard.set("", forKey: ADUrl)
            UserDefaults.standard.set("", forKey: ADDeadline)
            UserDefaults.standard.synchronize()
        }
    }
    
    fileprivate func startTimer() {
        countTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(coundown), userInfo: nil, repeats: true)
        count = adShowTime
        RunLoop.main.add(countTimer!, forMode: .commonModes)
    }
    
    @objc fileprivate func coundown() {
        
        count -= 1
        countButton.setTitle("跳过\(count)", for: .normal)
        if count == 0 {
            dismiss()
        }
    }
    
    @objc fileprivate func pushToAdVC() {
        // 点击广告图时，广告图消失，同时像首页发送通知，并把广告页对应的地址传给首页
        dismiss()
        NotificationCenter.default.post(name: ADTapActionNotification, object: nil)
    }
    
    @objc fileprivate func dismiss() {
        countTimer?.invalidate()
        countTimer = nil
        UIView.animate(withDuration: 0.3, animations: { 
            self.alpha = 0.0
        }) { (_) in
            self.removeFromSuperview()
        }
    }
    
    fileprivate lazy var adImagView: UIImageView = {
        let imgView = UIImageView(frame: self.frame)
        imgView.isUserInteractionEnabled = true
        imgView.contentMode = .scaleAspectFill
        imgView.clipsToBounds = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(pushToAdVC))
        imgView.addGestureRecognizer(tap)
        return imgView
    }()
    
    fileprivate lazy var countButton: UIButton = {
        let button = UIButton(type: UIButtonType.custom)
        button.frame = CGRect(x: UIScreen.main.bounds.width - 84, y: 30, width: 60, height: 30)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.setTitleColor(UIColor.white, for: .normal)
        button.backgroundColor = UIColor(red: 38.0 / 255.0, green: 38.0 / 255.0, blue: 38.0 / 255.0, alpha: 0.6)
        button.layer.cornerRadius = 4
        button.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
        return button
    }()

}
